package com.weavernorth.attendance.timer;

import com.weavernorth.attendance.util.ToSapUtil;
import com.weavernorth.util.Logger4jUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 异常考勤数据推送到sap定时任务
 *
 * @author XvFei
 * @version V1.0 created by XvFei at 2020-02-18
 * @description 用于同步行业资讯数据
 */
public class UnusualAttendaceToSapTimer extends BaseCronJob {
    /**
     * 日志打印对象
     */
//    private static Logger log = LoggerFactory.getLogger(UnusualAttendaceToSapTimer.class);
    private static org.apache.log4j.Logger log= Logger4jUtil.getLoggerByName("/action/weavernorth/attendance/timer/UnusualAttendaceToSapTimer/");

    @Override
    public void execute() {
        log.info("异常考勤数据推送到SAP开始！！！");

        BaseBean aa = new BaseBean();
        //获取properties中接口地址值
        String strRealUrl = Util.null2String(aa.getPropValue("kqtosap", "kqtosapurl"));
        //请假主表名称
        String strMtableName = Util.null2String(aa.getPropValue("kqtosap", "mtablename"));
        //截止第几天
        int intAbortDay = Util.getIntValue(aa.getPropValue("kqtosap", "abortday"));
        //不推送人id
        String strNoPushUser = Util.null2String(aa.getPropValue("kqtosap", "nopushuserid"));

        //上一个月第一天
        String strPreMonthFirstDate = ToSapUtil.getPreMonthFirstDate();
        //测试
        //String strPreMonthFirstDate = "2020-05-01";

        //上一个月最后一天
        String strPreMonthLastDate = ToSapUtil.getPreMonthLastDate();
        //测试
        //  String strPreMonthLastDate ="2020-05-31";

        //当前月的第五天
        String strCurMonthDay = ToSapUtil.getCurYearAndMonth(intAbortDay);

        //用于查询的RecordSet
        RecordSet rsSelect = new RecordSet();
        RecordSet rsHrmSel = new RecordSet();
String strKqData="select * from (" +
        " select resourceid,kqdate,belatemins mins,1 kqtype from kq_format_detail " +
        " where belatemins > 0 and belatemins <= 60 " +
        " union all " +
        " select resourceid,kqdate,graveBeLateMins mins,1 kqtype from kq_format_detail " +
        " where graveBeLateMins > 0 and graveBeLateMins <= 60 " +
        " union all " +
        " select resourceid,kqdate,leaveearlymins mins,2 kqtype from kq_format_detail " +
        " where leaveearlymins > 0 and leaveearlymins <= 60 " +
        " union all " +
        " select resourceid,kqdate,graveLeaveEarlyMins mins,2 kqtype from kq_format_detail " +
        " where graveLeaveEarlyMins > 0 and graveLeaveEarlyMins <= 60 " +
        " ) where kqdate >= ? and kqdate <= ? order by resourceid desc,kqdate asc";
        //查询考勤异常数据：迟到/早退的数据  小于 60分钟的为迟到早退      kqtype 1：迟到   kqtype 2：早退
        rsSelect.executeQuery(strKqData,
                strPreMonthFirstDate, strPreMonthLastDate);
        log.info("查询考勤异常数据SQL(迟到(kqtype=1)/早退(kqtype=0)的数据)："+strKqData);
        //上一个人的id
        int intPreUserId = 0;
        //迟到或早退次数 30分钟以内个数
        int intNum = 0;

        //员工表编号
        String strUserWorkCode = "";

        List<Map<String, Object>> listParam = new ArrayList<Map<String, Object>>();
        //请假参数集合
        List<Map<String, Object>> listLeaveParam = new ArrayList<Map<String, Object>>();
        while (rsSelect.next()) {
            Map<String, Object> mapParam = new HashMap<String, Object>();
            //人员id
            int intCurUserId = Util.getIntValue(rsSelect.getString("resourceid"));
            //迟到或早退时间
            int intMins = Util.getIntValue(rsSelect.getString("mins"), 0);
            //考勤类型      1：迟到     2：早退
            int intKqType = Util.getIntValue(rsSelect.getString("kqtype"), 0);
            //考勤异常日期
            String strKqDate = Util.null2String(rsSelect.getString("kqdate"));

            //如果不是同一个人则迟到次数置空 上一个人的id改成当前人员id
            if (intPreUserId != intCurUserId) {
                intNum = 0;
                intPreUserId = intCurUserId;
            }
//            log.info("当前人员id:"+intCurUserId);
//            log.info("不推送人员:"+strNoPushUser);
//            log.info("时间:"+intMins);
            //判断当前人员是否推送考勤异常数据
            if (ToSapUtil.isCanToSapByUserId(intCurUserId) && strNoPushUser.indexOf("," + intCurUserId + ",") == -1) {

                //查询该人员的编号
                rsHrmSel.executeQuery("select workcode from hrmresource where id=?", intCurUserId);
                rsHrmSel.next();
                strUserWorkCode = Util.null2String(rsHrmSel.getString("workcode"));

                //判断迟到或早退时间  小于等于30分钟  则记录一次次数
                if (intMins <= 30) {
                    intNum++;
                    //大于三次则推迟sap
                    //得到当前人的考勤类型
                    String strLateTypeOne = ToSapUtil.getUserIdType(intCurUserId, "cddma");
                    String strEarlyType = ToSapUtil.getUserIdType(intCurUserId, "ztdma");
                    //log.info("迟到30分钟以内类型:"+strLateTypeOne+",早退30分钟以内类型:"+strEarlyType);
                    //修改逻辑：30分钟以内的迟到、早退,2次（含）以上每次扣50
                    if (intNum > 1 && intKqType == 1 && !"".equals(strLateTypeOne)) {
                        mapParam.put("kqtype", strLateTypeOne);
                        mapParam.put("workcode", strUserWorkCode);
                        mapParam.put("salarytype", "5023");
                        mapParam.put("num", 50);
                        mapParam.put("kqdate", strKqDate);
                        listParam.add(mapParam);

                    } else if (intNum > 1 && intKqType == 2 && !"".equals(strEarlyType)) {
                        mapParam.put("kqtype", strEarlyType);
                        mapParam.put("workcode", strUserWorkCode);
                        mapParam.put("salarytype", "5023");
                        mapParam.put("num", 50);
                        mapParam.put("kqdate", strKqDate);
                        listParam.add(mapParam);

                    }

                }


                //大于30分钟 推送sap
                else if (intMins <= 60) {
                    String strLateTypeOne = ToSapUtil.getUserIdType(intCurUserId, "cddmb");
                    String strEarlyType = ToSapUtil.getUserIdType(intCurUserId, "ztdmb");
                    // log.info("迟到30分钟以上类型:"+strLateTypeOne+",早退30分钟以上类型:"+strEarlyType+",人员编码:"+strUserWorkCode);
                    if (intKqType == 1 && !"".equals(strLateTypeOne)) {
                        mapParam.put("kqtype", strLateTypeOne);
                        mapParam.put("workcode", strUserWorkCode);
                        mapParam.put("salarytype", "5023");
                        mapParam.put("num", 100);
                        mapParam.put("kqdate", strKqDate);
                        listParam.add(mapParam);
                    } else if (!"".equals(strEarlyType)) {
                        mapParam.put("kqtype", strEarlyType);
                        mapParam.put("workcode", strUserWorkCode);
                        mapParam.put("salarytype", "5023");
                        mapParam.put("num", 100);
                        mapParam.put("kqdate", strKqDate);
                        listParam.add(mapParam);
                    }
                }
            }
        }


        //查询考勤异常数据：漏签
        rsSelect.executeQuery("select * from ( " +
                        " select resourceid,kqdate,1 forgettype from kq_format_detail where forgotcheckMins > 0 " +
                        " union all " +
                        " select resourceid,kqdate,2 forgettype from kq_format_detail where forgotbeginworkcheckmins > 0 " +
                        " ) where kqdate >= ? and kqdate <= ? order by resourceid desc,kqdate asc ",
                strPreMonthFirstDate, strPreMonthLastDate);

        //忘打卡次数
        int intForgetNum = 0;
        //上一个人的id(忘打卡)
        int intForgetPreUserId = 0;
        while (rsSelect.next()) {
            Map<String, Object> mapParam = new HashMap<String, Object>();
            //人员id
            int intCurUserId = Util.getIntValue(rsSelect.getString("resourceid"));
            //考勤类型      1：签到没签退     2：签退没签到
            int intForgetType = Util.getIntValue(rsSelect.getString("forgettype"), 0);
            //考勤异常日期
            String strKqDate = Util.null2String(rsSelect.getString("kqdate"));

            //如果不是同一个人则忘打卡次数置空 上一个人的id改成当前人员id
            if (intForgetPreUserId != intCurUserId) {
                intForgetNum = 0;
                intForgetPreUserId = intCurUserId;
            }

            //判断当前人员是否推送考勤异常数据
            if (ToSapUtil.isCanToSapByUserId(intCurUserId) && strNoPushUser.indexOf("," + intCurUserId + ",") == -1) {

                //查询该人员的编号
                rsHrmSel.executeQuery("select workcode from hrmresource where id=?", intCurUserId);
                rsHrmSel.next();
                strUserWorkCode = Util.null2String(rsHrmSel.getString("workcode"));

                String strForgetType = ToSapUtil.getUserIdType(intCurUserId, "lqdm");
                //log.info("漏签类型:"+strForgetType);

                intForgetNum++;
                //考勤忘打卡次数超过三次    签到未签退和签退未签到
//                if (intForgetNum >= 3 && intForgetType == 1 && !"".equals(strForgetType)) {
//                    mapParam.put("kqtype", strForgetType);
//                    mapParam.put("workcode", strUserWorkCode);
//                    mapParam.put("salarytype", "5024");
//                    mapParam.put("num", 100);
//                    mapParam.put("kqdate", strKqDate);
//                    listParam.add(mapParam);
//                } else if (intForgetNum >= 3 && intForgetType == 2 && !"".equals(strForgetType)) {
//                    mapParam.put("kqtype", strForgetType);
//                    mapParam.put("workcode", strUserWorkCode);
//                    mapParam.put("salarytype", "5024");
//                    mapParam.put("num", 100);
//                    mapParam.put("kqdate", strKqDate);
//                    listParam.add(mapParam);
//                }
                //修改逻辑：漏签（忘打卡）第2次（含）开始每次算0.5天旷工
                String strKgdm = ToSapUtil.getUserIdType(intCurUserId, "kgdm");
                if (intForgetNum >= 2 && intForgetType == 1 && !"".equals(strForgetType)) {
                    mapParam.put("kqtype", strKgdm);
                    mapParam.put("workcode", strUserWorkCode);
                    mapParam.put("salarytype", "5030");
                    mapParam.put("num", 0.5);
                    mapParam.put("kqdate", strKqDate);
                    listLeaveParam.add(mapParam);
                } else if (intForgetNum >= 2 && intForgetType == 2 && !"".equals(strForgetType)) {
                    mapParam.put("kqtype", strKgdm);
                    mapParam.put("workcode", strUserWorkCode);
                    mapParam.put("salarytype", "5030");
                    mapParam.put("num", 0.5);
                    mapParam.put("kqdate", strKqDate);
                    listLeaveParam.add(mapParam);
                }

            }
        }

        //如果有数据，则推送到SAP，没有不执行sap数据推送
        if (listParam.size() > 0) {
            String strResult = null;
            String strRequestXml = ToSapUtil.getRequestXml(listParam, "0015").toString();
            log.info("传递的RequestXml：" + strRequestXml);
            try {
                strResult = ToSapUtil.sendPost(strRealUrl, strRequestXml, "utf-8");
            } catch (IOException e) {
                e.printStackTrace();
                log.error("推送考勤异常出现错误(迟到、早退、漏签)：" + e.getMessage());
            }
            log.info("推送考勤异常返回结果(迟到、早退、漏签)：" + strResult);

        } else {
            log.info("推送考勤异常(迟到、早退、漏签)：没有可推送的数据！");
        }

        //--------------------------------------------------------------------------------------------------------------

        String strSqls="select resourceid,sum(absent_day) allabsentday from ( " +
                " select resourceid,kqdate,case when belatemins <= 240 then 0.5 else 1 end absent_day " +
                " from kq_format_detail where belatemins > 60 " +
                " union all " +
                " select resourceid,kqdate,case when graveBeLateMins <= 240 then 0.5 else 1 end absent_day " +
                " from kq_format_detail where graveBeLateMins > 60 " +
                " union all " +
                " select resourceid,kqdate,case when leaveearlymins <= 240 then 0.5 else 1 end absent_day " +
                " from kq_format_detail where leaveearlymins > 60 " +
                " union all " +
                " select resourceid,kqdate,case when graveLeaveEarlyMins <= 240 then 0.5 else 1 end absent_day " +
                " from kq_format_detail where graveLeaveEarlyMins > 60 " +
                " union all " +
                " select resourceid,kqdate,case when absenteeismmins <= 240 then 0.5 else 1 end absent_day " +
                " from kq_format_detail where absenteeismmins > 0 " +
                " ) where kqdate >= ? and kqdate <= ? group by resourceid order by resourceid asc";
        //查询考勤异常数据：旷工
        rsSelect.executeQuery(strSqls,strPreMonthFirstDate, strPreMonthLastDate);
        log.info("旷工汇总，sql语句："+strSqls);
        while (rsSelect.next()) {
            Map<String, Object> mapParam = new HashMap<String, Object>();
            //人员id
            int intCurUserId = Util.getIntValue(rsSelect.getString("resourceid"));

            //判断当前人员是否推送考勤异常数据
            if (ToSapUtil.isCanToSapByUserId(intCurUserId) && strNoPushUser.indexOf("," + intCurUserId + ",") == -1) {
                //旷工天数
                double dblAbsentDays = Util.getDoubleValue(rsSelect.getString("allabsentday"), 0.0);
                //考勤异常日期
                String strKqDate = strPreMonthLastDate;

//                try {
                //查询该人员的编号
                rsHrmSel.executeQuery("select workcode from hrmresource where id=?", intCurUserId);
                rsHrmSel.next();
                strUserWorkCode = Util.null2String(rsHrmSel.getString("workcode"));
//                    ResourceComInfo rci = new ResourceComInfo();
//                    strUserWorkCode = rci.getWorkcode(String.valueOf(intCurUserId));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    log.error("获取人员编号出错：" + e.getMessage());
//                }
                String strDblAbsentType = ToSapUtil.getUserIdType(intCurUserId, "kgdm");
                //log.info("旷工类型:"+strDblAbsentType);
                if (!"".equals(strDblAbsentType)) {
                    mapParam.put("kqtype", strDblAbsentType);
                    mapParam.put("workcode", strUserWorkCode);
                    mapParam.put("salarytype", "5030");
                    mapParam.put("num", dblAbsentDays);
                    mapParam.put("kqdate", strKqDate);
                    listLeaveParam.add(mapParam);
                }
            }
        }

//
//String sql="select fmdt.detail_resourceId,fmdt.detail_newLeaveType,fmdt.detail_fromDate," +
//                " fmdt.detail_toDate,fmdt.detail_duration" +
//                " from formtable_main_" + strMtableName + "_dt1 fmdt inner join formtable_main_" + strMtableName +
//                " fm on fmdt.mainid = fm.id " +
//                " inner join workflow_requestbase wrb on wrb.requestid = fm.requestid and wrb.currentnodetype = ? " +
//                " and wrb.lastoperatedate < ? " +
//                " where fmdt.detail_fromdate >= ? and fmdt.detail_todate <= ? " +
//                " and fmdt.detail_newleavetype in(6,7) order by fmdt.detail_resourceId asc";
        //查询考勤异常数据：请假
//        rsSelect.executeQuery("select fmdt.detail_resourceId,fmdt.detail_newLeaveType,fmdt.detail_fromDate," +
//                " fmdt.detail_toDate,fmdt.detail_duration" +
//                " from formtable_main_" + strMtableName + "_dt1 fmdt inner join formtable_main_" + strMtableName +
//                " fm on fmdt.mainid = fm.id " +
//                " inner join workflow_requestbase wrb on wrb.requestid = fm.requestid and wrb.currentnodetype = ? " +
//                " and wrb.lastoperatedate < ? " +
//                " where fmdt.detail_fromdate >= ? and fmdt.detail_todate <= ? " +
//                " and fmdt.detail_newleavetype in(6,7) order by fmdt.detail_resourceId asc", 3,
//                strCurMonthDay,
//                strPreMonthFirstDate, strPreMonthLastDate);
        //log.info("查询事假表名sql:"+sql+","+strMtableName+",strCurMonthDay:"+strCurMonthDay+",strPreMonthFirstDate:"+strPreMonthFirstDate+",strPreMonthLastDate:"+strPreMonthLastDate);


        //----修改

        //获取请假人员
        ToSapUtil toSapUtil = new ToSapUtil();

        List<Map<String, String>> listQjdata = toSapUtil.getLeaveData(strPreMonthFirstDate, strPreMonthLastDate);
        for (Map<String, String> map : listQjdata) {
            // while(rsSelect.next()){
            Map<String, Object> mapParam = new HashMap<String, Object>();
            //人员id
//            int intCurUserId = Util.getIntValue(rsSelect.getString("detail_resourceId"));
//            //考勤类型(请假)     6：事假     7：病假
//            int intLeaveType = Util.getIntValue(rsSelect.getString("detail_newLeaveType"), 0);
//            //考勤异常日期
//            String strKqDate = Util.null2String(rsSelect.getString("detail_fromDate"));
//            //请假时长
//            double dblLeaveDay = Util.getDoubleValue(rsSelect.getString("detail_duration"), 0.0);


            int intCurUserId = Util.getIntValue(map.get("resourceid"));
            //考勤类型(请假)     6：事假     7：病假
            int intLeaveType = Util.getIntValue(map.get("newleavetype"), 0);
            //考勤异常开始日期
            String strKqDate = Util.null2String(map.get("leavedate"));
            //考勤异常结束日期
            String strJsDate = Util.null2String(map.get("enddate"));
            //请假时长
            log.info("考勤开始日期："+strKqData+"考勤结束日期："+strJsDate);
            log.info("月初"+strPreMonthFirstDate+";月末："+strPreMonthLastDate);
            BigDecimal bigLeaveDay = new BigDecimal(Util.null2o(map.get("leavedays")));
            if (intLeaveType==7){
                //如果病假存在一整月时,请假天数固定为21.75（SAP要求）
                if (strKqData.equals(strPreMonthFirstDate)&&strJsDate.equals(strPreMonthLastDate)){
                    log.info("存在整月请假,则去全月");
                    bigLeaveDay=new BigDecimal(21.75);
                    log.info("人员resourceid为："+intCurUserId+";存在请整月病假");
                }
            }

            log.info("得到的请假时长:" + bigLeaveDay.toString());
            //查询是否有销假,并得到销假天数


            BigDecimal bigLeaveBackDays = toSapUtil.getLeavebackData(strPreMonthFirstDate, strPreMonthLastDate, intLeaveType, intCurUserId);
            log.info("得到的销假时长:" + bigLeaveBackDays.toString());
            double dblLeaveDay = bigLeaveDay.subtract(bigLeaveBackDays).doubleValue();
            log.info("最终得到的请假时长:" + dblLeaveDay);


            // double dblLeaveDay = Util.getDoubleValue(map.get("leavedays"), 0.0);

            //查询该人员的编号
            rsHrmSel.executeQuery("select workcode from hrmresource where id=?", intCurUserId);
            rsHrmSel.next();
            strUserWorkCode = Util.null2String(rsHrmSel.getString("workcode"));

            //判断当前人员是否推送考勤异常数据
            if (ToSapUtil.isCanToSapByUserId(intCurUserId) && strNoPushUser.indexOf("," + intCurUserId + ",") == -1) {
                //事假天数大于0，则同步数据
                String strThingLeaveType = ToSapUtil.getUserIdType(intCurUserId, "sjdm");
                String strSickType = ToSapUtil.getUserIdType(intCurUserId, "bjdm");
                // log.info("事假类型:"+strThingLeaveType+",病假类型:"+strSickType);
                if (intLeaveType == 6 && dblLeaveDay > 0 && !"".equals(strThingLeaveType)) {
                    mapParam.put("kqtype", strThingLeaveType);
                    mapParam.put("workcode", strUserWorkCode);
                    mapParam.put("salarytype", "5019");
                    mapParam.put("num", dblLeaveDay);
                    mapParam.put("kqdate", strKqDate);
                    listLeaveParam.add(mapParam);
                } else if (intLeaveType == 7 && dblLeaveDay > 0 && !"".equals(strSickType)) {
                    mapParam.put("kqtype", strSickType);
                    mapParam.put("workcode", strUserWorkCode);
                    mapParam.put("salarytype", "5028");
                    mapParam.put("num", dblLeaveDay);
                    mapParam.put("kqdate", strKqDate);
                    listLeaveParam.add(mapParam);
                }
            }
        }

        log.info("集合长度:" + listLeaveParam.size());

        if (listLeaveParam.size() > 0) {
            String strLeaveResult = null;
            String strLeaveRequestXml = ToSapUtil.getRequestXml(listLeaveParam, "2010").toString();
            log.info("传递的strLeaveRequestXml：" + strLeaveRequestXml);
            try {
                strLeaveResult = ToSapUtil.sendPost(strRealUrl, strLeaveRequestXml, "utf-8");
            } catch (IOException e) {
                e.printStackTrace();
                log.error("推送考勤异常出现错误(请假),旷工：" + e.getMessage());
            }
            log.info("推送考勤异常返回结果(请假),旷工：" + strLeaveResult);
        } else {
            log.info("推送考勤异常(请假),旷工：没有可推送的数据！");
        }

        log.info("异常考勤数据推送到SAP结束！！！");
    }
}
